package com.yuandian.customer.perception.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yuandian.api.customer_perception.po.LowFrequenceSystemParams;
import com.yuandian.api.customer_perception.po.LowFrequencyHistoryExportParams;
import com.yuandian.api.customer_perception.po.LowFrequencyOverviewParams;
import com.yuandian.api.customer_perception.vo.HisExportListVo;
import com.yuandian.api.customer_perception.vo.LowFrequencyHistoryExportVo;
import com.yuandian.api.customer_perception.vo.SystemOverview;
import com.yuandian.api.customer_perception.vo.SystemPieDataVo;
import com.yuandian.bpm.common.core.util.R;
import com.yuandian.bpm.common.data.resolver.ParamResolver;
import com.yuandian.constant.ConfigKey;
import com.yuandian.constant.Constants;
import com.yuandian.customer.perception.mapper.HisExportListMapper;
import com.yuandian.customer.perception.service.IHisExportListService;
import com.yuandian.customer.perception.service.ILowFrequencySysOverviewService;
import com.yuandian.utils.BeanUtils;
import com.yuandian.utils.DateTool;
import com.yuandian.utils.PageDataInfo;
import com.yuandian.utils.PdfUtil;
import com.yuandian.utils.poi.WordUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;
import java.util.zip.ZipOutputStream;

/**
 * 说明：历史导出列表service实现
 * @Author yanjun
 * @Date 2021年4月14日 下午3:28:04
 */
@Service
public class HisExportListServiceImpl implements IHisExportListService {



	@Autowired
	private HisExportListMapper hisExportListMapper;

	@Autowired
	private ILowFrequencySysOverviewService sysOverviewService;


	/**
	 * 查询历史导出文件记录列表
	 * @param params 低频受理业务概况请求对象
	 * @return 通用分页对象
	 */
	//@DS("khgzData")
	@Override
	public PageDataInfo queryHisExportList(LowFrequencyHistoryExportParams params) {
		Page<LowFrequencyHistoryExportVo> page = new Page<>(params.getPageNum(), params.getPageSize());
		List<LowFrequencyHistoryExportVo> list = hisExportListMapper.queryHisExportList(params, page);
		return new PageDataInfo(page, list);
	}

	/**
	 * 根据id导出历史导出记录列表(pdf)
	 * @param params 低频受理业务概况请求对象
	 * @return 通用返回对象
	 */
	@Override
	public R exportHisExportListByIds(LowFrequencyOverviewParams params) {
		// 查询历史导出记录列表
		List<HisExportListVo> list = hisExportListMapper.queryHisExportListByIds(params.getIds());
		List<Object[]> dataList = new ArrayList<>();
		list.forEach(l -> {
			dataList.add(new Object[] {l.getSystemName(), l.getBusinessName(), l.getAcceptState(),
					l.getWeekCount(), l.getAvgWeekCount(), l.getMonthCount(), l.getAvgMonthCount(),
					l.getThreeMonthCount(), l.getAvgThreeMonthCount(), l.getLastTime(), l.getSuggest(), l.getExportTime()});
		});
		// 生成pdf文件
		String filePath = PdfUtil.generalPdf("历史导出列表_" + System.currentTimeMillis() + ".pdf",
				new String[] {"系统名称", "业务名称", "受理状态", "上周受理量", "周日均受理量", "上月受理量", "月日均受理量",
						"上三月受理量", "季日均受理量", "最后发生时间", "建议", "导出时间"}, dataList);
		return R.ok(filePath);
	}

	/**
	 * 导出历史导出记录列表(pdf)
	 * @param params 低频受理业务概况请求对象
	 * @return 通用返回对象
	 */
	@Override
	public R exportHisExportList(LowFrequencyOverviewParams params) {
		// 查询历史导出记录列表
		PageDataInfo info = queryHisExportList(null);
		List<HisExportListVo> list = BeanUtils.cast(info.getData());
		List<Object[]> dataList = new ArrayList<>();
		list.forEach(l -> {
			dataList.add(new Object[] {l.getSystemName(), l.getBusinessName(), l.getAcceptState(),
					l.getWeekCount(), l.getAvgWeekCount(), l.getMonthCount(), l.getAvgMonthCount(),
					l.getThreeMonthCount(), l.getAvgThreeMonthCount(), l.getLastTime(), l.getSuggest(), l.getExportTime()});
		});
		// 生成pdf文件
		String filePath = PdfUtil.generalPdf("历史导出列表_" + System.currentTimeMillis() + ".pdf",
				new String[] {"系统名称", "业务名称", "受理状态", "上周受理量", "周日均受理量", "上月受理量", "月日均受理量",
						"上三月受理量", "季日均受理量", "最后发生时间", "建议", "导出时间"}, dataList);
		return R.ok(filePath);
	}

	/**
	 * 一键导出历史导出记录列表(新)(PDF)
	 *
	 * @param params 低频受理业务概况请求对象
	 * @return 通用返回对象
	 */
	@Override
	public R exportHisExportListNew(LowFrequenceSystemParams params) {

		// 文件保存路径
		String savePath = ParamResolver.getStr(ConfigKey.DPSL_FILE_PATH);
		//pdf标题
		String title = "系统低频空置业务统计表" + Constants.DOUBLE_SPACE +  params.getStartTime().substring(0, 10) + "~" + params.getEndTime().substring(0, 10);

		//查询数据
		List<SystemOverview> list = sysOverviewService.querySystemOverviewList(params).getSystemOverviewVoList();
		if (CollectionUtils.isEmpty(list)) {
			// 生成pdf文件
			String filePath = PdfUtil.customDownPDF(title + "_" + System.currentTimeMillis() + ".pdf", savePath, title,
					new String[]{"序号", "域", "系统名称", "正常", "低频及空置"}, new ArrayList<>());
			return R.ok(filePath);
		}

		//如果指定了某个域,过滤其他
		if (params.getSystemDomainId() != null) {
			list = list.stream().filter(s -> params.getSystemDomainId().equals(s.getSystemDomainId())).collect(Collectors.toList());
		}

		ArrayList<SystemPieDataVo> orderList = new ArrayList<>();
		//系统id对应的域名
		HashMap<Integer, String> systemDomainNameMap = new HashMap<>();
		for (SystemOverview vo : list) {
			//加入排序List,等待排序
			orderList.addAll(vo.getData());
			//设置系统id对应域名,用于导出列表展示
			for (SystemPieDataVo dataVo : vo.getData()) {
				systemDomainNameMap.put(dataVo.getSystemId(), vo.getSystemDomainName());
			}
		}

		//根据低频和空置比例排序
		/*Collections.sort(orderList, (SystemPieDataVo data1, SystemPieDataVo data2) -> {
			double rate1 = (double) data1.getAbnormalValue() / data1.getTotal();
			double rate2 = (double) data2.getAbnormalValue() / data2.getTotal();
			if (rate1 < rate2 || (rate1 == rate2 && data1.getAbnormalValue() < data2.getAbnormalValue())) {
				return 1;
			}
			return -1;
		});*/
		Collections.sort(orderList, (SystemPieDataVo data1, SystemPieDataVo data2) -> {
			double rate1 = data1.getTotal() == 0 ? 0 : (double) data1.getAbnormalValue() / data1.getTotal();
			double rate2 = data2.getTotal() == 0 ? 0 : (double) data2.getAbnormalValue() / data2.getTotal();
			if (rate1 < rate2
					|| (rate1 == rate2 && data1.getAbnormalValue() < data2.getAbnormalValue())
					|| (rate1 == rate2 && data1.getAbnormalValue() == data2.getAbnormalValue() && data1.getNormalValue() < data2.getNormalValue())) {
				return 1;
			}
			return -1;
		});

		//计算百分比,以供填入pdf中
		List<Object[]> dataList = new ArrayList<>();
		int index = 1;
		for (SystemPieDataVo vo : orderList) {
			//计算正常,低频及空置百分比
			String normalValueProportion = "(0%)";
			String abnormalValueProportion = "(0%)";
			if (vo.getNormalValue() != 0 || vo.getAbnormalValue() != 0) {
				int normalValue = vo.getNormalValue();
				int abnormalValue = vo.getAbnormalValue();
				normalValueProportion = "(" + String.format("%.2f", ((double) normalValue / ((double) normalValue + (double) abnormalValue)) * 100) + "%)";
				abnormalValueProportion = "(" + String.format("%.2f", ((double) abnormalValue / ((double) normalValue + (double) abnormalValue)) * 100) + "%)";
			}
			dataList.add(new Object[]{(index++), systemDomainNameMap.get(vo.getSystemId()), vo.getSystemName(), vo.getNormalValue() + normalValueProportion, vo.getAbnormalValue() + abnormalValueProportion});
		}

		// 生成pdf文件
		String filePath = PdfUtil.customDownPDF(title + "_" + System.currentTimeMillis() + ".pdf", savePath, title,
				new String[]{"序号", "域", "系统名称", "正常", "低频及空置"}, dataList);
		return R.ok(filePath);
	}

	/**
	 * 从历史导出表下载文件（PDF 形式）(new-20210628)
	 *
	 * @param fileName 文件名
	 */
	//@DS("khgzData")
	@Override
	public void downLoadHistoryPdfFile(String fileName, HttpServletResponse response) {
		// 文件保存路径
		String savePath = ParamResolver.getStr(ConfigKey.DPSL_FILE_PATH);
		File file = new File(savePath + "/" + fileName);
		WordUtil.downloadPdf(file, response);
	}

	/**
	 * 从历史导出表下载文件到本地（压缩包形式）(new-20210628)
	 * @param dpslFlieExportRoute 路径
	 * @param params 低频受理业务概况请求对象
	 * @return 通用返回对象
	 */
	//@DS("khgzData")
	@Override
	public void downLoadHistoryFileZip(LowFrequencyHistoryExportParams params,String dpslFlieExportRoute, HttpServletResponse response) {
//        exportType为1时为全部导出

		// 查询历史导出记录列表
		List<LowFrequencyHistoryExportVo> historyFileList = hisExportListMapper.queryHisExportListNoPage(params);
		List<File> fileList = new ArrayList<>();
		historyFileList.forEach(res -> {
			fileList.add(new File(dpslFlieExportRoute + "/" + res.getFileName()));
		});
		// 获取压缩包名字
		String zipFileName = packFileToZip(fileList,dpslFlieExportRoute);
		WordUtil.downloadZip(new File(dpslFlieExportRoute + "/" + zipFileName), response);
	}

	/**
	 * 将文件打包成zip，返回zip文件名(打包成功后不删除源文件)
	 *
	 * @param fileList
	 * @return
	 */
	private String packFileToZip(List<File> fileList,String dpslFlieExportRoute) {
		String zipFileName = DateTool.yyyy_MM_dd_HH_mm_ss(new Date()).replace("-", "").replace(":", "").replace(" ", "").trim() + ".zip";
		ZipOutputStream zos = null;
		try {
			File zipFile = new File(dpslFlieExportRoute + "/" + zipFileName);
			if (!zipFile.exists()) {
				zipFile.createNewFile();
			}
			zos = new ZipOutputStream(new FileOutputStream(zipFile));
			WordUtil.zipFile(fileList, zos);
		} catch (IOException e1) {
			e1.printStackTrace();
		} finally {
			if (zos != null) {
				try {
					zos.close();
				} catch (IOException e1) {
					e1.printStackTrace();
				}
			}
		}
		return zipFileName;
	}
}
